package com.server.modules.api.web;

import com.alibaba.fastjson.JSON;
import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.*;
import com.pingplusplus.model.Charge;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.Webhooks;
import com.server.common.security.RSASignUtils;
import com.server.common.security.RSAUtils;
import com.server.common.utils.IPUtils;
import com.server.common.utils.PathUtils;
import com.server.common.utils.StringUtils;
import com.server.modules.api.Base.BaseAppController;
import com.server.modules.api.entity.BankCardInfoModel;
import com.server.modules.api.service.ISettlementAPIService;
import com.server.modules.api.utils.Constants;
import com.server.modules.api.vo.*;
import com.server.modules.sys.common.StaticDefine;
import com.server.modules.sys.entity.User;
import com.server.modules.sys.entity.bank.BankCardBin;
import com.server.modules.sys.entity.charge.ChargeRecord;
import com.server.modules.sys.entity.loan.CustomPay;
import com.server.modules.sys.entity.loan.Loan;
import com.server.modules.sys.entity.member.Member;
import com.server.modules.sys.entity.member.MemberBankcard;
import com.server.modules.sys.entity.settlement.Settlement;
import com.server.modules.sys.entity.settlement.item.SettlementItem;
import com.server.modules.sys.service.bank.BankCardBinService;
import com.server.modules.sys.service.loan.CustomPayService;
import com.server.modules.sys.service.member.MemberBankcardService;
import com.server.modules.sys.service.settlement.SettlementService;
import com.server.modules.sys.service.settlement.item.SettlementItemService;
import com.server.modules.sys.utils.AmountUtils;
import com.server.modules.sys.utils.LogUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.*;

/**
 * Created by Administrator on 2016/9/18.
 */
@Controller
@RequestMapping(value = "/api/pay")
public class PaymentController extends BaseAppController {

    @Resource
    private MemberBankcardService memberBankcardService;

    @Resource
    BankCardBinService bankCardBinService;

    @Resource
    private SettlementService settlementService;

    @Resource
    private SettlementItemService settlementItemService;

    @Resource
    private CustomPayService customPayService;
    @Resource
    private ISettlementAPIService settlementAPIService;
    /**
     * 支付渠道：alipay-支付宝移动端
     */
    private static final String CHARGE_CHANNEL_ALIPAY = "alipay";

    /**
     * 支付渠道：wx-微信移动端
     */
    private static final String CHARGE_CHANNEL_WECHAT = "wx";
    Properties properties = PathUtils.getProperties("application.properties");
    /**
     * 设置ping++key
     *
     * @return
     */
    private void setPingppKey() {

        String keyType = properties.getProperty("pingppKey");
        String apiKeyTest= properties.getProperty("pingxx_apiKeyTest");
        String apiKey= properties.getProperty("pingxx_apiKey");
        if ("liveKey".equals(keyType)) {
            // 生产key
            Pingpp.apiKey = apiKey;
        } else {
            // 其他情况都使用测试key
            Pingpp.apiKey = apiKeyTest;
        }
    }


    @ResponseBody
    @RequestMapping(value = "/getCharge")
    public BaseQueryVo getCharge(HttpServletRequest request, PaymentVO paymentVO) throws Exception {
        BaseQueryVo baseQueryVo = new BaseQueryVo();
      /* if (!checkLogin(paymentVO)) {
            return returnMsgAPIService.getRet(Constants.errLogin);
        }*/
        if (StringUtils.isEmpty(paymentVO.getOrderNum())){//没有流水号
            return returnMsgAPIService.getRet(Constants.incompleteData);
        }
        CustomPay customPay = applyLoanAPIService.findCustomPayByOrders(paymentVO.getOrderNum());
        if (customPay == null){//没有该笔流水
            return returnMsgAPIService.getRet(Constants.notFound);
        }

        if (!customPay.getMemberid().equals(paymentVO.getMemberId())){//memberId不匹配
            return returnMsgAPIService.getRet(Constants.payWrong);
        }

        Integer paymanetVO = Integer.parseInt(paymentVO.getAmount());

        String orderFlag = customPay.getOrderFlag();
        //支付定金
        if(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WATTINGPAY.equals(orderFlag)){
            Integer customPayAmount = Integer.parseInt(customPay.getServiceCharge());
            if (StringUtils.isEmpty(customPay.getServiceCharge())){ //金额有误
                return returnMsgAPIService.getRet(Constants.payWrongSerivceCharge);
            }
            if (!customPayAmount.equals(paymanetVO) ){
                return returnMsgAPIService.getRet(Constants.notEqualSerivceCharge);
            }
            // 设置ping++key
            setPingppKey();
            //检查参数是否完整
            Map<String, Object> chargeMap = new HashMap<String, Object>();
            // 计算订单总金额
            if (StringUtils.isNotEmpty(paymentVO.getAmount())) {
                try {
                    int amount = Integer.parseInt(paymentVO.getAmount());
                    chargeMap.put("amount", amount); // 金额，单位为分，例 100 表示 1.00 元，233 表示 2.33 元
                } catch (Exception e) {
                    baseQueryVo.setRetCode(-1);
                    baseQueryVo.setRetMsg(e.getMessage());
                    return baseQueryVo;
                }
            } else {
                return returnMsgAPIService.getRet(Constants.incompleteData);
            }
            chargeMap.put("currency", "cny");
            if (StringUtils.isNotEmpty(paymentVO.getSubject())) {
                chargeMap.put("subject", paymentVO.getSubject());
            } else {
                return returnMsgAPIService.getRet(Constants.incompleteData);
            }
            chargeMap.put("body", "Your Body");
            chargeMap.put("order_no", paymentVO.getOrderNum()); // 订单号，请参考官网文档格式说明
            if (StringUtils.isNotEmpty(paymentVO.getChannel())) {
                chargeMap.put("channel", paymentVO.getChannel()); // 渠道字段
            } else {
                return returnMsgAPIService.getRet(Constants.incompleteData);
            }
            chargeMap.put("client_ip", IPUtils.getIpAddr(request)); // 客户端的 IP 地址
            Map<String, String> app = new HashMap<String, String>();
            String appId= properties.getProperty("pingxx_appId");
            app.put("id", appId);
            chargeMap.put("app", app);
            Charge charge = Charge.create(chargeMap);
            if (charge != null) {
                baseQueryVo.setData(charge);
                baseQueryVo.setRetCode(0);
                baseQueryVo.setRetMsg("创建成功");
            }
            ChargeRecord chargeRecord = new ChargeRecord();
            chargeRecord.setAccountId(paymentVO.getChannel());
            Member member = memberService.get(paymentVO.getMemberId());
            if (member != null){
                if (member.getBalance() != null)
                    chargeRecord.setOldBalance(member.getBalance());
                else chargeRecord.setOldBalance("0");
            }
            chargeRecord.setMemberId(paymentVO.getMemberId());
            chargeRecord.setAmount(customPay.getServiceCharge());
            User user = new User();
            user.setId("1");
            user.setCreateDate(new Date());
            chargeRecord.setOrders(customPay.getOrderNum());
            chargeRecord.setCharge(charge.toString());
            chargeRecord.setCreateBy(user);
            chargeRecord.setUpdateBy(user);
            chargeRecord.setSignature(RSAUtils.sign(
                    (chargeRecord.getAmount()
                            +chargeRecord.getMemberId()
                            +chargeRecord.getCharge()
                            +chargeRecord.getOldBalance()
                            +chargeRecord.getBalance())
                            .getBytes(),RSASignUtils.getKeyByKeyFileName("privateKey.keystore")));
            chargeRecord.setRecordFlag("0");
            try {
                chargeRecordService.save(chargeRecord);
            }catch (Exception e){
                logger.error(e.getMessage());
                baseQueryVo.setRetCode(Constants.unKnowError);
                baseQueryVo.setRetMsg(e.getMessage());
                return baseQueryVo;
            }
            return baseQueryVo;
        }else if(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WATTINGPAYSETTLEMENT.equals(orderFlag)){
            //付尾款
            Settlement settlement=new Settlement();
            settlement.setMemberId(customPay.getMemberid());
            //settlement.setOrders(customPay.getOrderNum());
            settlement.setCustomPayId(customPay.getId());
            settlement.setType(StaticDefine.SETTLEMENT_TYPE.SETTLEMENT);
            List<Settlement> list = settlementService.findList(settlement);

            if(!CollectionUtils.isEmpty(list)){
                Settlement settlement1 = list.get(0);
                SettlementItem item=new SettlementItem();
                item.setSettlementId(settlement1.getId());
                List<SettlementItem> items = settlementItemService.findList(item);
                Long amout=0l;
                for (SettlementItem settlementItem : items) {
                    String type = settlementItem.getType();
                    if(StaticDefine.SETTLEMENT_ITEM_TYPE.IN.equals(type)){
                        amout+=  settlementItem.getAmount();
                    }else{
                        amout-=  settlementItem.getAmount();
                    }
                }
                Long paymanetVOLong=Long.parseLong(paymanetVO+"");
                //金额不对
                if(!amout.equals(paymanetVOLong)){
                    return returnMsgAPIService.getRet(Constants.notEqualSerivceCharge);
                }
                // 设置ping++key
                setPingppKey();
                //检查参数是否完整
                Map<String, Object> chargeMap = new HashMap<String, Object>();
                // 计算订单总金额
                if (StringUtils.isNotEmpty(paymentVO.getAmount())) {
                    try {
                        int amount = Integer.parseInt(paymentVO.getAmount());
                        chargeMap.put("amount", amount); // 金额，单位为分，例 100 表示 1.00 元，233 表示 2.33 元
                    } catch (Exception e) {
                        baseQueryVo.setRetCode(-1);
                        baseQueryVo.setRetMsg(e.getMessage());
                        return baseQueryVo;
                    }
                } else {
                    return returnMsgAPIService.getRet(Constants.incompleteData);
                }
                chargeMap.put("currency", "cny");
                if (StringUtils.isNotEmpty(paymentVO.getSubject())) {
                    chargeMap.put("subject", paymentVO.getSubject());
                } else {
                    return returnMsgAPIService.getRet(Constants.incompleteData);
                }
                chargeMap.put("body", "Your Body");
                chargeMap.put("order_no", settlement1.getOrders()); // 订单号，请参考官网文档格式说明
                if (StringUtils.isNotEmpty(paymentVO.getChannel())) {
                    chargeMap.put("channel", paymentVO.getChannel()); // 渠道字段
                } else {
                    return returnMsgAPIService.getRet(Constants.incompleteData);
                }
                chargeMap.put("client_ip", IPUtils.getIpAddr(request)); // 客户端的 IP 地址
                Map<String, String> app = new HashMap<String, String>();
                String appId= properties.getProperty("pingxx_appId");
                app.put("id", appId);
                chargeMap.put("app", app);
                Charge charge = Charge.create(chargeMap);
                if (charge != null) {
                    baseQueryVo.setData(charge);
                    baseQueryVo.setRetCode(0);
                    baseQueryVo.setRetMsg("创建成功");
                }
                ChargeRecord chargeRecord = new ChargeRecord();
                chargeRecord.setAccountId(paymentVO.getChannel());
                Member member = memberService.get(paymentVO.getMemberId());
                if (member != null){
                    if (member.getBalance() != null)
                        chargeRecord.setOldBalance(member.getBalance());
                    else chargeRecord.setOldBalance("0");
                }
                chargeRecord.setMemberId(paymentVO.getMemberId());
                chargeRecord.setAmount(customPay.getServiceCharge());
                User user = new User();
                user.setId("1");
                user.setCreateDate(new Date());
                chargeRecord.setOrders(customPay.getOrderNum());
                chargeRecord.setCharge(charge.toString());
                chargeRecord.setCreateBy(user);
                chargeRecord.setUpdateBy(user);
                chargeRecord.setSignature(RSAUtils.sign(
                        (chargeRecord.getAmount()
                                +chargeRecord.getMemberId()
                                +chargeRecord.getCharge()
                                +chargeRecord.getOldBalance()
                                +chargeRecord.getBalance())
                                .getBytes(),RSASignUtils.getKeyByKeyFileName("privateKey.keystore")));
                chargeRecord.setRecordFlag("0");
                try {
                    chargeRecordService.save(chargeRecord);
                }catch (Exception e){
                    logger.error(e.getMessage());
                    baseQueryVo.setRetCode(Constants.unKnowError);
                    baseQueryVo.setRetMsg(e.getMessage());
                    return baseQueryVo;
                }
                return baseQueryVo;
            }else{
                baseQueryVo.setRetCode(Constants.unKnowError);
                baseQueryVo.setRetMsg("获取结算信息失败");
                return baseQueryVo;
            }


        }
        else{
            baseQueryVo.setRetCode(Constants.customPayError);
            baseQueryVo.setRetMsg("贷款申请状态错误");
            return baseQueryVo;
        }
    }
    /**
     * 查询支付凭据
     *
     * @throws ChannelException
     * @throws APIException
     * @throws APIConnectionException
     * @throws InvalidRequestException
     * @throws AuthenticationException
     */
    @RequestMapping(value =  "/retrieveCharge" , method = RequestMethod.POST)
    @ResponseBody
    public BaseQueryVo retrieveCharge(HttpServletRequest request, PaymentVO paymentVO) {
        // 设置ping++key
        setPingppKey();
        Charge charge = null;
        BaseQueryVo baseQueryVo = new BaseQueryVo();
       try {
            charge = Charge.retrieve(request.getParameter(paymentVO.getId()));
        } catch (AuthenticationException e) {
            e.printStackTrace();
            baseQueryVo.setRetCode(Constants.notFound);
            baseQueryVo.setRetMsg(e.getMessage());
            return baseQueryVo;
        } catch (InvalidRequestException e) {
            e.printStackTrace();
            baseQueryVo.setRetCode(Constants.notFound);
            baseQueryVo.setRetMsg(e.getMessage());
            return baseQueryVo;
        } catch (APIConnectionException e) {
            e.printStackTrace();
            baseQueryVo.setRetCode(Constants.notFound);
            baseQueryVo.setRetMsg(e.getMessage());
            return baseQueryVo;
        } catch (APIException e) {
            e.printStackTrace();
            baseQueryVo.setRetCode(Constants.notFound);
            baseQueryVo.setRetMsg(e.getMessage());
            return baseQueryVo;
        } catch (ChannelException e) {
            e.printStackTrace();
            baseQueryVo.setRetCode(Constants.notFound);
            baseQueryVo.setRetMsg(e.getMessage());
            return baseQueryVo;
        }catch (RateLimitException e){
            e.printStackTrace();
            baseQueryVo.setRetCode(Constants.notFound);
            baseQueryVo.setRetMsg(e.getMessage());
            return baseQueryVo;
        }
        if (charge != null) {
            baseQueryVo.setRetCode(0);
            baseQueryVo.setRetMsg("获取成功");
            baseQueryVo.setData(charge);
            return baseQueryVo;
        } else {
            return returnMsgAPIService.getRet(Constants.notFound);
        }
    }

    /**
     * 获取支付结果
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getPaymentResult")
    @ResponseBody
    public void getPaymentResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader reader = request.getReader();
        StringBuffer buffer = new StringBuffer();
        String string;
        while ((string = reader.readLine()) != null) {
            buffer.append(string);
        }
        reader.close();
        // 解析异步通知数据
        Event event = Webhooks.eventParse(buffer.toString());
        if ("charge.succeeded".equals(event.getType())) {
            response.setStatus(200);
            ChargeVo charge = JSON.parseObject(event.getData().getObject().toString(),ChargeVo.class);
            if (charge.getPaid()) {
                StringBuffer err = new StringBuffer();
                // 支付成功
                String orderNum = charge.getOrder_no();
                // 根据订单号查询订单,订单的金额是总金额
              ChargeRecord chargeRecord = new ChargeRecord();
                if (orderNum == null){
                    return;
                }
                chargeRecord.setOrders(orderNum);
              List<ChargeRecord> chargeRecordList =  chargeRecordService.findList(chargeRecord);
              if (chargeRecordList != null && chargeRecordList.size() >0){
                  ChargeRecord tmpOrder = chargeRecordList.get(0);//获取现有数据，并校验是否被篡改过
                  if (!RSAUtils.verify((tmpOrder.getAmount()
                          +tmpOrder.getMemberId()
                          +tmpOrder.getCharge()
                          +tmpOrder.getOldBalance()
                          +tmpOrder.getBalance())
                          .getBytes(),RSASignUtils.getKeyByKeyFileName("publicKey.keystore"),tmpOrder.getSignature())){
                        //数据已被篡改。不需要做更新操作，计入异常日志中，等待进一步数据分析
                      LogUtils.saveLog(request,"数据被篡改id["+tmpOrder.getId()+"] 回调不能正常处理，请人工处理");
                  }
                  Member member = memberService.get(tmpOrder.getMemberId());
                  double balance = 0.0;
                      String balance1 = member.getBalance();
                      if(StringUtils.isNotBlank(balance1)){
                          try {
                              balance = Double.parseDouble(member.getBalance());
                          }catch (Exception e){
                              e.printStackTrace();
                          }
                      }else{
                          member.setBalance("0");
                      }
                  tmpOrder.setOldBalance(""+balance);
                  Integer account =Integer.parseInt(tmpOrder.getAmount());
                  tmpOrder.setBalance(""+(balance+account));
                  member.setBalance( Integer.valueOf(member.getBalance()) + Integer.valueOf(account)+"");
                      try {
                          chargeRecord.setSignature(RSASignUtils.sign(
                                  (chargeRecord.getAmount()
                                          +chargeRecord.getMemberId()
                                          +chargeRecord.getCharge()
                                          +chargeRecord.getOldBalance()
                                          +chargeRecord.getBalance())
                                          .getBytes(),RSASignUtils.getKeyByKeyFileName("privateKey.keystore")));
                          chargeRecord.setRecordFlag("1");
                          CustomPay customPay = new CustomPay();
                          customPay.setOrderNum(orderNum);
                          List<CustomPay> customPays = customPayService.findList(customPay);
                          if (customPays == null || customPays.size() == 0){
                                    return;
                          }
                          customPay = customPays.get(0);
                          //付定金
                          if(customPay.getOrderFlag().equals(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WATTINGPAY)){
                              //更新申请订单状态 为待审核（付了订金，应该是待审核状态了）
                              customPay.setOrderFlag(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WAITTINGCHECK);
                          }else if(customPay.getOrderFlag().equals(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WATTINGPAYSETTLEMENT)){
                              //付款尾款  付尾款后是贷款成功状态
                              customPayService.paySettlement(customPay,request);
                              customPay.setOrderFlag(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.LOANSUCCESS);
                          }
                          customPayService.save(customPay); //更新申请订单状态
                          chargeRecordService.save(tmpOrder); //修改充值流水状态
                          memberService.save(member);   //修改用户余额状态
                          List<String> userList = new ArrayList<String>(1);
                          userList.add(member.getHxUsername());
                          Map<String,String > msg = new HashedMap();
                          msg.put("type","text");
                          msg.put("msg","订单号为："+charge.getOrder_no()+"的申请已收到支付请求，请耐心等待客服人员与您进行联系");
                          Map<String,String > ext = new HashedMap();
                          List<ApplyLoan> applyLoanList= applyLoanAPIService.findApplyLoanList(customPay);
                          if (applyLoanList!=null && applyLoanList.size() >0){
                              ApplyLoan applyLoan = applyLoanList.get(0);
                              ext.put("objId",chargeRecord.getOrders());
                              ext.put("data", JSON.toJSONString(applyLoan));
                              ext.put("type","2");//1为产品，2为申请记录
                              //imService.sendMessages("users",userList,msg,"客服经理",ext);
                              //推系统消息
                              imService.sendSysMessages(userList,msg,ext);
                          }
                      }catch (Exception e){
                            logger.error(e.getMessage());
                      }
              }
            }
        }
    }
    /**
     * 获取支付结果
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getPaymentResultTest")
    @ResponseBody
    public void getPaymentResultTest(HttpServletRequest request, HttpServletResponse response) throws Exception {
            response.setStatus(200);
                StringBuffer err = new StringBuffer();
                // 支付成功
                String orderNum = "14810815384463491051";
                // 根据订单号查询订单,订单的金额是总金额
                ChargeRecord chargeRecord = new ChargeRecord();
                if (orderNum == null){
                    return;
                }
                chargeRecord.setOrders(orderNum);
                List<ChargeRecord> chargeRecordList =  chargeRecordService.findList(chargeRecord);
                if (chargeRecordList != null && chargeRecordList.size() >0){
                    ChargeRecord tmpOrder = chargeRecordList.get(0);//获取现有数据，并校验是否被篡改过
                    if (!RSAUtils.verify((tmpOrder.getAmount()
                            +tmpOrder.getMemberId()
                            +tmpOrder.getCharge()
                            +tmpOrder.getOldBalance()
                            +tmpOrder.getBalance())
                            .getBytes(),RSASignUtils.getKeyByKeyFileName("publicKey.keystore"),tmpOrder.getSignature())){
                        //数据已被篡改。不需要做更新操作，计入异常日志中，等待进一步数据分析
                        LogUtils.saveLog(request,"数据被篡改id["+tmpOrder.getId()+"] 回调不能正常处理，请人工处理");
                    }
                    Member member = memberService.get(tmpOrder.getMemberId());
                    double balance = 0.0;
                    if (member.getBalance() != null){
                        balance = Double.parseDouble(member.getBalance());
                    }
                    tmpOrder.setOldBalance(""+balance);
                    Integer account =Integer.parseInt(tmpOrder.getAmount());
                    tmpOrder.setBalance(""+(balance+account));
                    member.setBalance( Integer.valueOf(member.getBalance()) + Integer.valueOf(account)+"");
                    try {
                        chargeRecord.setSignature(RSASignUtils.sign(
                                (chargeRecord.getAmount()
                                        +chargeRecord.getMemberId()
                                        +chargeRecord.getCharge()
                                        +chargeRecord.getOldBalance()
                                        +chargeRecord.getBalance())
                                        .getBytes(),RSASignUtils.getKeyByKeyFileName("privateKey.keystore")));
                        chargeRecord.setRecordFlag("1");
                        CustomPay customPay = new CustomPay();
                        customPay.setOrderNum(orderNum);
                        List<CustomPay> customPays = customPayService.findList(customPay);
                        if (customPays == null || customPays.size() == 0){
                            return;
                        }
                        customPay = customPays.get(0);
                        //付定金
                        if(customPay.getOrderFlag().equals(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WATTINGPAY)){
                            //更新申请订单状态 为待审核（付了订金，应该是待审核状态了）
                            customPay.setOrderFlag(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WAITTINGCHECK);
                        }else if(customPay.getOrderFlag().equals(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WATTINGPAYSETTLEMENT)){
                            //付款尾款  付尾款后是贷款成功状态
                            customPayService.paySettlement(customPay,request);
                            customPay.setOrderFlag(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.LOANSUCCESS);
                        }
                        customPayService.save(customPay); //更新申请订单状态
                        chargeRecordService.save(tmpOrder); //修改充值流水状态
                        memberService.save(member);   //修改用户余额状态
                        List<String> userList = new ArrayList<String>(1);
                        userList.add(member.getHxUsername());
                        Map<String,String > msg = new HashedMap();
                        msg.put("type","text");
                        msg.put("msg","订单号为："+orderNum+"的申请已收到支付请求，请耐心等待客服人员与您进行联系");
                        Map<String,String > ext = new HashedMap();
                        List<ApplyLoan> applyLoanList= applyLoanAPIService.findApplyLoanList(customPay);
                        if (applyLoanList!=null && applyLoanList.size() >0){
                            ApplyLoan applyLoan = applyLoanList.get(0);
                            ext.put("objId",chargeRecord.getOrders());
                            ext.put("data", JSON.toJSONString(applyLoan));
                            ext.put("type","2");//1为产品，2为申请记录
                            //imService.sendMessages("users",userList,msg,"客服经理",ext);
                            //推系统消息
                            imService.sendSysMessages(userList,msg,ext);
                        }
                    }catch (Exception e){
                        logger.error(e.getMessage());
                    }
                }
    }
    @ResponseBody
    @RequestMapping(value = "/getPaymentList", method = RequestMethod.POST)
    public BaseQueryVo getPaymentList(HttpServletRequest request,PaymentVO paymentVO){
        try {
            if (!checkLogin(paymentVO)) {
                return returnMsgAPIService.getRet(Constants.errLogin);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return returnMsgAPIService.getRet(Constants.errLogin);
        }
        BaseQueryVo baseQueryVo = new BaseQueryVo();
        setPageConfig(paymentVO);
        List<ChargeRecord> chargeRecordList =   memberAPIService.getChargeRecordList(paymentVO);
            baseQueryVo.setRetCode(0);
            baseQueryVo.setRetMsg("查询成功");
            baseQueryVo.setData(chargeRecordList);
        return baseQueryVo;
    }
    //银行卡绑定
    @ResponseBody
    @RequestMapping(value = "/bindBankCard", method = RequestMethod.POST)
    public BaseQueryVo bindBankCard(HttpServletRequest request,BankCardPo vo){
        try {
            if (!checkLogin(vo)) {
                return returnMsgAPIService.getRet(Constants.errLogin);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return returnMsgAPIService.getRet(Constants.errLogin);
        }

        if (StringUtils.isEmpty(vo.getCard_number())){//卡号
            return  returnMsgAPIService.getRet(Constants.incompleteData);
        }
        if (StringUtils.isEmpty(vo.getId_name())){//姓名
            return  returnMsgAPIService.getRet(Constants.incompleteData);
        }
        if (StringUtils.isEmpty(vo.getId_number())){//身份证号
            return  returnMsgAPIService.getRet(Constants.incompleteData);
        }
        if (StringUtils.isEmpty(vo.getPhone_number())){ //电话号码
            return  returnMsgAPIService.getRet(Constants.incompleteData);
        }
        MemberBankcard memberBankcard = bankCardPingxxService.getBankcardByMemberId(vo.getMemberId());

        if (memberBankcard!=null){
            return  returnMsgAPIService.getRet(Constants.bindBankCardError);
        }else {
            memberBankcard = bankCardPingxxService.getBankcardByCardNum(vo.getCard_number());
            if (memberBankcard!=null && !vo.getMemberId().equals(memberBankcard.getMemberId())){
                return  returnMsgAPIService.getRet(Constants.bindBankCardError);
            }
        }
        BaseQueryVo baseQueryVo = new BaseQueryVo();
        setPageConfig(vo);
        BankCardInfoVo bankCardInfoVo = new BankCardInfoVo();
        bankCardInfoVo.setType("bank_card");
        BankCardInfoModel bankCardInfoModel = new BankCardInfoModel();
        bankCardInfoModel.setCard_number(vo.getCard_number());
        bankCardInfoModel.setId_name(vo.getId_name());
        bankCardInfoModel.setId_number(vo.getId_number());
        bankCardInfoModel.setPhone_number(vo.getPhone_number());
        bankCardInfoVo.setData(bankCardInfoModel);
        baseQueryVo=   bankCardPingxxService.identifyBankCard(bankCardInfoVo);
        if (baseQueryVo.getRetCode()==0){
            memberBankcard = new MemberBankcard();
            memberBankcard.setMemberId(vo.getMemberId());
            memberBankcard.setCardNumber(bankCardInfoModel.getCard_number());
            memberBankcard.setIdName(bankCardInfoModel.getId_name());
            memberBankcard.setPhoneNumber(bankCardInfoModel.getPhone_number());
            memberBankcard.setIdNumber(bankCardInfoModel.getId_number());
            User user = new User();
            user.setId("1");
            memberBankcard.setCreateDate(new Date());
            memberBankcard.setCreateBy(user);
            memberBankcard.setUpdateBy(user);
            memberBankcard.setUpdateDate(new Date());
            memberBankcard.setDelFlag("0");
            BankCardBin bankCardBin = bankCardPingxxService.getBankCardBinByCardNum(bankCardInfoModel.getCard_number());
            if (bankCardBin!=null){
                memberBankcard.setBankName(bankCardBin.getBankName());
                memberBankcard.setCardName(bankCardBin.getCardName());
                memberBankcard.setCardType(bankCardBin.getCardType());
            }else {
                bankCardBin = new BankCardBin();
                bankCardBin.setDemo(bankCardInfoModel.getCard_number());
                bankCardBin.setDelFlag("2");//未查询到相应的卡bin
                bankCardBin.setCardDigits(""+bankCardInfoModel.getCard_number().trim().length());
                bankCardBin.setCreateBy(user);
                bankCardBin.setCreateDate(new Date());
                bankCardBin.setUpdateBy(user);
                bankCardBin.setUpdateDate(new Date());
                bankCardBinService.save(bankCardBin);
            }
            memberBankcardService.save(memberBankcard);
        }
        return baseQueryVo;
    }
    //获取绑定银行卡列表
    @ResponseBody
    @RequestMapping(value = "/getBindedBankCard", method = RequestMethod.POST)
    public BaseQueryVo getBindedBankCard(HttpServletRequest request,BaseQueryVo vo){
        try {
            if (!checkLogin(vo)) {
                return returnMsgAPIService.getRet(Constants.errLogin);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return returnMsgAPIService.getRet(Constants.errLogin);
        }
        MemberBankcard memberBankcard = bankCardPingxxService.getBankcardByMemberId(vo.getMemberId());
        BaseQueryVo baseQueryVo = new BaseQueryVo();
        baseQueryVo.setData(-1);
        baseQueryVo.setRetMsg("未知错误");
        if (memberBankcard!=null){
            baseQueryVo.setRetCode(0);
            baseQueryVo.setRetMsg("查询成功");
            baseQueryVo.setData(memberBankcard);
        }else {
            return returnMsgAPIService.getRet(Constants.notFound);
        }
        return baseQueryVo;
    }
    //支付订金详情
    @ResponseBody
    @RequestMapping(value = "/payDepositDetails")
    public BaseQueryVo depositDetails(HttpServletRequest request,BaseQueryVo vo,String customPayId){
        try {
            if (!checkLogin(vo)) {
                return returnMsgAPIService.getRet(Constants.errLogin);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return returnMsgAPIService.getRet(Constants.errLogin);
        }
        try {
            PayDepositDetailsVo payDepositDetailsVo = new PayDepositDetailsVo();
            vo.setData(payDepositDetailsVo);
            String memberId = vo.getMemberId();
            if(StringUtils.isNotBlank(customPayId)){
                CustomPay customPay = customPayService.get(new CustomPay(customPayId));
                if(customPay!=null){
                    Loan loan = loanService.get(new Loan(customPay.getLoanid()));
                    payDepositDetailsVo.setLoanName(loan.getName());
                    payDepositDetailsVo.setLoanMemberLimit(AmountUtils.handelAmount(customPay.getMemberLoanLimit()));
                    payDepositDetailsVo.setRate(customPay.getRate());//利率
                    payDepositDetailsVo.setDepositAmount(AmountUtils.changeF2Y( customPay.getServiceCharge())+"元");
                    payDepositDetailsVo.setMember(memberService.get(new Member(memberId)));
                    payDepositDetailsVo.setApplyNotice("");
                    return vo;
                }else{
                    return returnMsgAPIService.getRet(Constants.notFound);
                }
            }else{
                return returnMsgAPIService.getRet(Constants.notFound);
            }
        }catch (Exception e) {
            logger.error(e.getMessage());
            return returnMsgAPIService.getRet(Constants.unKnowError);
        }

    }
}
